﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.WaiGaoQiao;
using WaiGaoQiaoWeb.Models;
using AutoMapper;
using WaiGaoQiaoWeb.JsonEntities;
using System.Text;

namespace WaiGaoQiaoWeb.Controllers
{
    public class ArticleController : Controller
    {
        //
        // GET: /Con_Goods/
        private Work_ArticleInfo conInfo = new Work_ArticleInfo();
        private Work_ArticleUnit unit = new Work_ArticleUnit();
        public ActionResult ArticleIndex()
        {
            return View();
        }
        /// <summary>
        /// 获取某个物品规格列表
        /// </summary>
        /// <returns></returns>
        public MultiSelectList GetUnitList(int priorid, IList<string> strList)
        {
            IList<Work_ArticleUnit> listUnit = null;
            if (priorid > 0)
            {
                listUnit = unit.GetAllCon_ArticleUnit("inner join work_article WA on aid=WA.id where A.aid=" + priorid + "");
                return new MultiSelectList(listUnit, "Id", "Unit", strList);

            }
            else
            {
                listUnit = new List<Work_ArticleUnit>();
                return new MultiSelectList(listUnit, "Id", "Unit", strList);
            }

        }
        /// <summary>
        /// 获取领取类型
        /// </summary>
        /// <returns></returns>
        public IList<SelectListItem> GetStorageType()
        {
            IDictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "个人物资");
            dic.Add(2, "班组物资");
            IList<SelectListItem> selectList =
             dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
            return selectList;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ID"></param>
        public ActionResult ArticleEdit(string Id, int? ParentId)
        {
            ViewBag.StorageType = GetStorageType();

            ParentId = ParentId.HasValue ? ParentId : 0;
            Work_ArticleInfo info;
            ArticleVM goodsVM = new ArticleVM();
            //ViewData["UnitList"] = GetUnitList(0, goodsVM.UnitList);
            int id = 0;
            if ((Id != null) && (Id != ""))
            {
                id = int.Parse(Id);
            }
            if (id > 0)
            {
                info = conInfo.GetCon_ArticleById(id);
                if (info != null)
                {
                    Mapper.CreateMap<Work_ArticleInfo, ArticleVM>();
                    goodsVM = Mapper.Map<Work_ArticleInfo, ArticleVM>(info);
                }
                else
                {
                    goodsVM = new ArticleVM();
                }  
                ViewData["UnitList"] = GetUnitList(id, goodsVM.UnitList);
            }
            // 数据
            else if ((ParentId != null) && (ParentId != 0))
            {
                ViewData["UnitList"] = GetUnitList(0, goodsVM.UnitList);
                goodsVM = new ArticleVM();
                goodsVM.PriorId = int.Parse(ParentId.ToString());
            }
            else if (Id == "" && ParentId == 0)
            {
                ViewData["UnitList"] = GetUnitList(0, goodsVM.UnitList);
                goodsVM = new ArticleVM();
            }
            return View(goodsVM);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="goodsVM"></param>
        /// <param name="?"></param>
        /// <param name="Id"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public ActionResult SaveWork_Article(ArticleVM goodsVM)
        {
            int flag = 0;
            Work_ArticleInfo goodsInfo;
            //if (ModelState.IsValid)
            //{
            if (goodsVM != null)
            {

                Mapper.CreateMap<ArticleVM, Work_ArticleInfo>();
                goodsInfo = Mapper.Map<ArticleVM, Work_ArticleInfo>(goodsVM);

                flag = conInfo.SaveWork_Article(goodsInfo);
            }
            //}
            return Json(flag);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="pVM"></param>
        /// <returns></returns>
        public ActionResult GetWork_ArticleList(PageVM pVM)
        {
            int intParentId = 0;
            if (pVM.key.ToString() != "")
            {
                intParentId = int.Parse(pVM.key.ToString());
                if (intParentId == 0)
                {
                    //return Json(true);
                }
            }
            string strCondtion = "and PriorID = " + intParentId;
            int groupCount = conInfo.GetWork_ArticleCount(strCondtion);
            IList<Work_ArticleInfo> list = conInfo.GetAllCon_Article(strCondtion, pVM.rp, pVM.page);
            JsonFlexiGridData flexigridObject = new JsonFlexiGridData();
            flexigridObject.page = pVM.page;
            flexigridObject.total = groupCount;
            List<string> v;
            foreach (Work_ArticleInfo ddi in list)
            {
                v = new List<string>();
                v.Add(ddi.ID.ToString());
                v.Add(ddi.ArticleNO);
                v.Add(ddi.ArticleName);
                v.Add(RtnStringUnit(ddi.ArticleUnit));
                v.Add(ddi.GetType == 1 ? "个人物资" : "班组物资");
                v.Add(ddi.PriorId.ToString());
                v.Add(ddi.Color);


                FlexiGridRow cell = new FlexiGridRow()
                {
                    id = ddi.ID.ToString(),
                    cell = v
                };
                flexigridObject.rows.Add(cell);
            }
            return Json(flexigridObject);
        }
        /// <summary>
        /// 返回物资规格
        /// </summary>
        /// <param name="strUnit"></param>
        /// <returns></returns>
        public string RtnStringUnit(string strUnit)
        {
            StringBuilder rtnString=new StringBuilder ();
            if (!string.IsNullOrEmpty(strUnit))
            {
                if (strUnit.IndexOf(',')>0)
                {
                    string[] charUnit = strUnit.Split(',');
                    for (int i = 0; i < charUnit.Length; i++)
                    {
                        rtnString.Append(unit.GetCon_ArticleUnitById(Convert.ToInt32(charUnit[i])).Unit + ",");

                    }
                }
                else
                {
                    rtnString.Append(unit.GetCon_ArticleUnitById(Convert.ToInt32(strUnit)).Unit);
                }
            }
            return rtnString.ToString();
        }
        public JsonResult RtnStringUnitForJson(string strUnit)
        {
            StringBuilder rtnString = new StringBuilder();
            if (!string.IsNullOrEmpty(strUnit))
            {
                if (strUnit.IndexOf(',') > 0)
                {
                    string[] charUnit = strUnit.Split(',');
                    for (int i = 0; i < charUnit.Length; i++)
                    {
                        rtnString.Append(unit.GetCon_ArticleUnitById(Convert.ToInt32(charUnit[i])).Unit + ",");

                    }
                }
                else
                {
                    rtnString.Append(unit.GetCon_ArticleUnitById(Convert.ToInt32(strUnit)).Unit);
                }
            }
            return Json(rtnString.ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryWork_Article()
        {
            IList<Work_ArticleInfo> dmlist = conInfo.GetAllCon_Article("and PriorID = 0");
            List<JsonTreeNode> nodes = new List<JsonTreeNode>();
            foreach (var item in dmlist)
            {
                JsonTreeNode cnode = new JsonTreeNode();
                cnode.id = item.ID.ToString();
                cnode.text = item.ArticleName;
                cnode.value = item.ArticleNO == null ? "" : item.ArticleNO;
                cnode.hasChildren = false;
                cnode.classes = "system";
                cnode.isexpand = false;
                cnode.complete = true;
                AddChildNode(cnode);
                nodes.Add(cnode);
            }
            return Json(nodes);
        }


        /// <summary>
        /// 递归添加子节点
        /// </summary>
        /// <param name="node"></param>
        private void AddChildNode(JsonTreeNode node)
        {
            int pid = Convert.ToInt32(node.id);
            IList<Work_ArticleInfo> mlist =
                conInfo.GetAllCon_Article("").Where(cinfo => cinfo.PriorId == pid).ToList();
            if (mlist != null)
            {
                foreach (var Childitem in mlist)
                {
                    node.hasChildren = true;
                    JsonTreeNode nodeChild = new JsonTreeNode();
                    nodeChild.id = Childitem.ID.ToString();
                    nodeChild.text = Childitem.ArticleName;
                    nodeChild.value = Childitem.ArticleNO == null ? "" : Childitem.ArticleNO;
                    nodeChild.hasChildren = false;
                    nodeChild.isexpand = true;
                    AddChildNode(nodeChild);
                    node.ChildNodes.Add(nodeChild);
                }
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteWork_Article(string GoodsIds)
        {
            bool flag = true;
            flag = conInfo.DeleteWork_Article(GoodsIds) > 0 ? true : false;
            return Json(flag);
        }

        /// <summary>
        /// 是否存在子节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult IsExistSubNode(int id)
        {
            bool flag = conInfo.IsExistSubNode(id);
            return Json(flag);
        }
    }
}
